<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <Tabs v-model:activeKey="activeKey">
      <TabPane :key="1" tab="基本信息" />
      <TabPane :key="2" tab="违法违规行为" />
    </Tabs>
    <BasicForm v-show="activeKey===1" @register="registerForm">
      <template #customCheckPerson="{ model, field }">
        <Select
          :options="checkPersonList"
          mode="tags"
          v-model:value="model[field]"
          :disabled="disabled"
        />
      </template>
      <template #customAccompanyPerson="{ model, field }">
        <Select
          :options="accompanyPersonList"
          mode="tags"
          v-model:value="model[field]"
          :disabled="disabled"
        />
      </template>
      <template #customLocation="{ model, field }">
        <Select
          :options="locationList"
          mode="tags"
          v-model:value="model[field]"
          :disabled="disabled"
        />
      </template>
      <template #customRecordPerson="{ model, field }">
        <Select
          :options="recordPersonList"
          mode="tags"
          v-model:value="model[field]"
          :disabled="disabled"
        />
      </template>
      <template #customDatePicker="{ model, field }">
        <DatePicker v-model:value="dateValue" format="YYYY-MM-DD" @change="onChange" :disabled="disabled"></DatePicker>
      </template>
    </BasicForm>
    <div v-show="activeKey===2" >
        <Form ref="formRef" :model="dynamicValidateForm">
          <FormItem
            v-for="(domain, index) in dynamicValidateForm.domains"
            :key="domain.id"
            :label="'问题' + (index + 1)"
            :name="index"
            :label-col="{span: 4}"
            :wrapper-col="{span: 20}"

          >
            <InputTextArea v-model:value="domain.problem" :rows="2" :key="domain.id" :disabled="disabled" />
            <Row class="enter-x">
              <Col :span="16">
                <BasicUpload v-model:value="domain.fileList.fileList" :maxSize="20" :maxNumber="10" :api="uploadApi" style="margin-top: 20px;" @preview-delete="onFileChange" @change="upload" :disabled="disabled"/>
              </Col>
              <Col :span="8">
                <Button danger @click="removeDomain(domain)" style="margin-top: 20px" :disabled="disabled" >
                移除当前问题
                </Button>
              </Col>
            </Row>
          </FormItem>
          <FormItem >
            <Button style="margin-left: 80px" @click="addDomain" >
              <PlusOutlined />
              添加问题
            </Button>
          </FormItem>
        </Form>
    </div>
  </BasicDrawer>
</template>
<script lang="ts">
import {defineComponent, reactive, ref, unref, UnwrapRef} from 'vue';
import {BasicForm, FormSchema, useForm} from '/@/components/Form/index';
import {miningTenantId} from './role.data';
import {MinusCircleOutlined, PlusOutlined, UploadOutlined} from '@ant-design/icons-vue';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
import {
  addProblem,
  AddTask,
  deleteProblem,
  detailProblem,
  personList,
  tenantList,
  updateProblem,
  updateTask
} from "/@/api/busi/record";
import {Button, Col, DatePicker, Form, Input, Row, Select, Tabs, Textarea, Upload} from 'ant-design-vue';
import moment from 'moment';
import {BasicUpload} from '/@/components/Upload';
import {uploadApi} from '/@/api/sys/upload';
import {useUserStore} from '/@/store/modules/user';
import {useMessage} from "/@/hooks/web/useMessage";
import {useGlobSetting} from "/@/hooks/setting";

interface fileObjs {
    fileName: string | null;
    objectUrl: string | null;
    path: string | null;
    url:string | null;
    name: string | null;
  }

  interface Domain {
    value: string;
    key: number;
    problem: string;
    fileObjs: fileObjs[];
    id: string | null;
    fileList: {
      fileList: [],
      ids: [],
    }
  }
  export default defineComponent({
    name: 'RoleDrawer',
    components: { InputTextArea: Input.TextArea, UploadOutlined, Upload, Row, Col, BasicUpload, BasicDrawer, BasicForm, PlusOutlined, DatePicker, Tabs, TabPane: Tabs.TabPane, Select, Button, MinusCircleOutlined, Form, FormItem: Form.Item },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const userStore = useUserStore();
      const activeKey = ref(1);
      const isUpdate = ref(false);
      const id = ref<string>('');
      const disabled = ref(false)
      const problemList =  ref<any>([])
      const checkPersonList = ref<any>([])
      const accompanyPersonList =  ref<any>([])
      const locationList =  ref<any>([])
      const recordPersonList =  ref<any>([])
      const getTitle = ref('新增检查记录')
      const dateValue = ref(undefined);
      const formRef = ref();
      const { createMessage }  = useMessage();
      const dynamicValidateForm: UnwrapRef<{ domains: Domain[] }> = reactive({
        domains: [],
      });
      const { uploadUrl } = useGlobSetting();
      const formSchema: FormSchema[] = [
        {
          field: 'name',
          label: '检查表名称',
          component: 'Input',
        },
        {
          field: 'miningTenant',
          label: '被检查单位',
          component: 'ApiSelect',
          componentProps: {
            api: tenantList,
            params: { page: 1, size: 1000, type: 'COMPANY'},
            resultField: 'returnData.list',
            labelField: 'name',
            valueField: 'name',
            immediate: true,
            async onChange(value) {
              if (value) {
                const id = await miningTenantId(value)
                console.log(value)
                console.log(id)
                const result = await personList({tenantId: 0})
                // const list = result.returnData.list;
                accompanyPersonList.value = [ {
                  value: 'lucy',
                  label: 'Lucy',
                }]
                console.log(result)
              }

            },
          },
        },
        {
          field: 'location',
          label: '检查地点',
          component: 'Select',
          slot: 'customLocation',
        },
        {
          field: 'checkTime',
          label: '检查时间',
          component: 'DatePicker',
          slot: 'customDatePicker',
        },
        {
          field: 'checkPerson',
          label: '检查人员',
          component: 'Select',
          slot: 'customCheckPerson',
        },
        {
          field: 'accompanyPerson',
          label: '陪同人员',
          component: 'Select',
          slot: 'customAccompanyPerson',
        },
        {
          field: 'recordPerson',
          label: '记录人员',
          component: 'Select',
          slot: 'customRecordPerson',
        },
      ];
      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });
      const [registerDrawer, { setDrawerProps, closeDrawer, changeLoading }] = useDrawerInner( async (data) => {
        changeLoading(true)
        setDrawerProps({ confirmLoading: true });
        await resetFields();
        isUpdate.value = !!data?.isUpdated;
        // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
        disabled.value = false;
        await updateSchema([
          {field: 'name', componentProps: {disabled: false}},
          {field: 'miningTenant', componentProps: {disabled: false}},
          {field: 'location', componentProps: {disabled: false}},
        ]);
        if (unref(isUpdate)) {
          getTitle.value = '编辑检查记录'
          id.value = data.record.id
          const params = {
            id: id.value,
          }
          const detail = await detailProblem(params);
          console.log(detail.returnData.problems);
          if (detail && detail.returnData.problems.length > 0) {
            detail.returnData.problems.forEach((item) => {
              const fileList:any = [];
              const ids: any = [];
              const files = item.fileObjs;
              files.forEach((it) => {
                fileList.push(it.url);
                ids.push(it.id);
              });
              item.fileList = {
                fileList: fileList,
                ids: ids,
              };
            })
          }
          dynamicValidateForm.domains = detail.returnData.problems;
          console.log(dynamicValidateForm.domains);
          data.record.checkTime = moment(data.record.checkTime, 'YYYY-MM-DD');
          dateValue.value = data.record.checkTime;
          await setFieldsValue({
            ...data.record,
          });
          if (data.isDetail) {
            getTitle.value = '检查记录详情';
            await updateSchema([
              {field: 'name', componentProps: {disabled: true}},
              {field: 'miningTenant', componentProps: {disabled: true}},
              {field: 'location', componentProps: {disabled: true}},
            ]);
            disabled.value = true;
          }
          setDrawerProps({ confirmLoading: false });
          changeLoading(false)
        }
      });

      async function handleSubmit() {
        try {
          if (activeKey.value == 1) {
            const values = await validate();
            setDrawerProps({ confirmLoading: true });
            const result = await tenantList({page: 1, size: 1000, type: 'COMPANY' })
            const list = result.returnData.list
            const miningTenant = values.miningTenant;
            const res = list.find((e => {
              return e.miningTenant = miningTenant;
            }))
            if (res) {
              values.miningTenantId = res.id;
            }
            values.accompanyTenant ="不知道"
            if (!isUpdate.value) {
              const data = {
                ...values,
              }
              await AddTask(data);
            } else {
              const data = {
                id: id.value,
                ...values,
              }
              await updateTask(data);
            }
          } else if (activeKey.value == 2) {
            console.log(dynamicValidateForm.domains)
            const updateData: any = [];
            const saveData: any = [];
            dynamicValidateForm.domains?.forEach((item) => {
              // item.path = item.objectUrl
              if (item.id) {
                const list = item.fileList.fileList;
                const ids = item.fileList.ids;
                const fileObjs:any = [];
                list.forEach((it, index) => {
                  fileObjs.push({
                    id: ids[index] ? ids[index] : null,
                    path: it,
                    fileName: it.substring(it.lastIndexOf('/oss-java-') + 10,it.lastIndexOf('?')) || ''
                  })
                })
                item.fileObjs = fileObjs;
                updateData.push(item);
              } else {
                const list = item.fileList.fileList;
                const ids = item.fileList.ids;
                const fileObjs:any = [];
                list.forEach((it, index) => {
                  fileObjs.push({
                    path: it,
                    id: ids[index] ?ids[index] : null,
                    fileName: it.substring(it.lastIndexOf('/oss-java-') + 10,it.lastIndexOf('?')) || ''
                  })
                })
                item.fileObjs = fileObjs;
                saveData.push(item);
              }
            })
            if (saveData.length > 0) {
              const params = {
                taskId: id.value,
                tenantId: userStore.getUserInfo.tenantId,
                problems: saveData,
              }
              await addProblem(params);
            }
            if (updateData.length > 0) {
              const data = {
                taskId: id.value,
                tenantId: userStore.getUserInfo.tenantId,
                problems: updateData
              }
              await updateProblem(data);
            }
            createMessage.success('添加或修改成功');
          }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      function onChange(date) {
        console.log(date)
        let time = moment(date).format('YYYY-MM-DD hh:mm:ss');
        setFieldsValue({ checkTime: time})
      }

      const removeDomain = async (item: Domain) => {
        let index = dynamicValidateForm.domains.indexOf(item);
        if (index !== -1) {
          dynamicValidateForm.domains.splice(index, 1);
        }
        console.log(item)
        await deleteProblem(item);
        createMessage.success('删除成功')
      };

      const addDomain = () => {
        dynamicValidateForm.domains.push({
          value: '',
          key: Date.now(),
          problem: '',
          fileObjs: [],
          id: null,
          fileList: {
            fileList: [],
            ids: []
          }
        });
      };

      function onFileChange(value) {
        const problems = dynamicValidateForm.domains
        console.log(problems)
        problems.forEach((item) => {
          const fileObjs = item.fileObjs;
          const idList = item.fileList.ids;
          const index = fileObjs.findIndex(it => it.url === value)
          if (index !== -1) {
            idList.splice(index,1)
            fileObjs.splice(index,1);
          }
          item.fileObjs = fileObjs
        })
        console.log(value)
      }

      function upload(value) {

        value.forEach((file) => {
          console.log(value)
          const problems = dynamicValidateForm.domains
          console.log(problems)
          problems.forEach((item) => {
            const fileObjs = item.fileObjs
            fileObjs.findIndex(it => it.url === file);
            item.fileObjs = fileObjs
          })
        })

      }

      return {
        removeDomain,
        addDomain,
        formRef,
        dynamicValidateForm,
        activeKey,
        registerDrawer,
        registerForm,
        handleSubmit,
        getTitle,
        dateValue,
        onChange,
        checkPersonList,
        accompanyPersonList,
        locationList,
        recordPersonList,
        disabled,
        problemList,
        uploadApi,
        uploadUrl,
        onFileChange,
        upload,
      };
    },
  });
</script>
